package com.example.managemyself.data.repository;

import android.app.Application;
import androidx.lifecycle.LiveData;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Calendar;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.database.DiaryEntryDao;
import com.example.managemyself.data.model.DiaryEntry;

/**
 * 日记仓库类，作为数据访问层和ViewModel之间的中介
 */
public class DiaryRepository {
    
    private final DiaryEntryDao diaryEntryDao;
    private final LiveData<List<DiaryEntry>> allDiaryEntries;
    private final ExecutorService executorService;
    
    public DiaryRepository(Application application) {
        AppDatabase database = AppDatabase.getInstance(application);
        diaryEntryDao = database.diaryEntryDao();
        allDiaryEntries = diaryEntryDao.getAllDiaryEntries();
        executorService = Executors.newFixedThreadPool(2); // 创建一个固定大小的线程池
    }
    
    public DiaryRepository(android.content.Context context) {
        AppDatabase database = AppDatabase.getInstance(context);
        diaryEntryDao = database.diaryEntryDao();
        allDiaryEntries = diaryEntryDao.getAllDiaryEntries();
        executorService = Executors.newFixedThreadPool(2);
    }
    
    // 获取所有日记
    public LiveData<List<DiaryEntry>> getAllDiaryEntries() {
        return allDiaryEntries;
    }
    
    // 根据ID获取日记
    public LiveData<DiaryEntry> getDiaryEntryById(int id) {
        return diaryEntryDao.getDiaryEntryById(id);
    }
    
    // 根据日期范围获取日记
    public LiveData<List<DiaryEntry>> getDiaryEntriesByDateRange(Date startDate, Date endDate) {
        return diaryEntryDao.getDiaryEntriesByDateRange(startDate, endDate);
    }
    
    // 根据日期获取日记
    public LiveData<DiaryEntry> getDiaryEntryByDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long startOfDay = cal.getTimeInMillis();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        long endOfDay = cal.getTimeInMillis();
        return diaryEntryDao.getDiaryEntryByDate(startOfDay, endOfDay);
    }
    
    // 根据日期获取日记（同步方法）
    public DiaryEntry getDiaryByDateSync(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long startOfDay = cal.getTimeInMillis();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        long endOfDay = cal.getTimeInMillis();
        return diaryEntryDao.getDiaryByDateSync(startOfDay, endOfDay);
    }
    
    // 搜索日记
    public LiveData<List<DiaryEntry>> searchDiaryEntries(String keyword) {
        return diaryEntryDao.searchDiaryEntries(keyword);
    }
    
    // 插入日记
    public void insertDiaryEntry(DiaryEntry diaryEntry) {
        executorService.execute(() -> diaryEntryDao.insertDiaryEntry(diaryEntry));
    }
    
    // 更新日记
    public void updateDiaryEntry(DiaryEntry diaryEntry) {
        executorService.execute(() -> diaryEntryDao.updateDiaryEntry(diaryEntry));
    }
    
    // 删除日记
    public void deleteDiaryEntry(DiaryEntry diaryEntry) {
        executorService.execute(() -> diaryEntryDao.deleteDiaryEntry(diaryEntry));
    }
    
    // 根据ID删除日记
    public void deleteDiaryEntryById(int id) {
        executorService.execute(() -> diaryEntryDao.deleteDiaryEntryById(id));
    }
    
    // 同步方法供AIDataManager使用
    public List<DiaryEntry> getRecentDiariesSync(int days) {
        try {
            return diaryEntryDao.getRecentDiariesSync(days);
        } catch (Exception e) {
            return new java.util.ArrayList<>();
        }
    }
    
    // ==================== 用户数据隔离方法 ====================
    
    // 根据用户ID获取所有日记
    public LiveData<List<DiaryEntry>> getDiaryEntriesByUserId(int userId) {
        return diaryEntryDao.getDiaryEntriesByUserId(userId);
    }
    
    // 根据ID和用户ID获取日记（验证权限）
    public LiveData<DiaryEntry> getDiaryEntryByIdAndUserId(int id, int userId) {
        return diaryEntryDao.getDiaryEntryByIdAndUserId(id, userId);
    }
    
    // 根据日期和用户ID获取日记
    public LiveData<DiaryEntry> getDiaryEntryByDateAndUserId(Date date, int userId) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long startOfDay = cal.getTimeInMillis();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        long endOfDay = cal.getTimeInMillis();
        return diaryEntryDao.getDiaryEntryByDateAndUserId(startOfDay, endOfDay, userId);
    }
    
    // 根据日期和用户ID获取日记（同步方法）
    public DiaryEntry getDiaryByDateAndUserIdSync(Date date, int userId) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long startOfDay = cal.getTimeInMillis();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        long endOfDay = cal.getTimeInMillis();
        return diaryEntryDao.getDiaryByDateAndUserIdSync(startOfDay, endOfDay, userId);
    }
    
    // 根据日期范围和用户ID获取日记
    public LiveData<List<DiaryEntry>> getDiaryEntriesByDateRangeAndUserId(Date startDate, Date endDate, int userId) {
        return diaryEntryDao.getDiaryEntriesByDateRangeAndUserId(startDate, endDate, userId);
    }
    
    // 根据关键词和用户ID搜索日记
    public LiveData<List<DiaryEntry>> searchDiaryEntriesByUserId(String keyword, int userId) {
        return diaryEntryDao.searchDiaryEntriesByUserId(keyword, userId);
    }
    
    // 根据ID同步获取日记（用于权限验证）
    public DiaryEntry getDiaryByIdSync(int id) {
        return diaryEntryDao.getDiaryByIdSync(id);
    }
    
    // 根据用户ID获取最近的日记（同步方法）
    public List<DiaryEntry> getRecentDiariesByUserIdSync(int userId, int days) {
        try {
            return diaryEntryDao.getRecentDiariesByUserIdSync(userId, days);
        } catch (Exception e) {
            return new java.util.ArrayList<>();
        }
    }
}
